package com.snap.awesomeserial.ui;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.widget.TextView;

import com.snap.awesomeserial.AppConfig;
import com.snap.awesomeserial.R;
import com.snap.awesomeserial.base.BaseActivity;
import com.snap.awesomeserial.bean.SerialPortDevice;
import com.snap.awesomeserial.serial.Cmd;
import com.snap.awesomeserial.serial.SerialPortHelper;
import com.snap.awesomeserial.ui.widget.AlphaLinearLayout;
import com.snap.awesomeserial.ui.widget.DialogView2;
import com.snap.awesomeserial.utils.ToastUtils;

import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;

public class TestMechanicalActivity extends BaseActivity {
    @BindView(R.id.title_tv)
    TextView titleTv;
    @BindView(R.id.bt4)
    TextView tempTv;
    @BindView(R.id.target_temp_ll)
    AlphaLinearLayout targetTempLl;
    @BindView(R.id.target_temp_tv)
    TextView targetTempTv;
    private SerialPortHelper serialPortHelper;
    private ScheduledExecutorService executor;
    private WriteAsyncTask writeAsyncTask;
    private Dialog dialog;

    public void onCallback(boolean isSuccess, byte[] data) {
        if (!isSuccess) {
            ToastUtils.get().showText("查询温度失败");
            return;
        }
        if (!Cmd.cmdValidate(data)) {
            ToastUtils.get().showText("查询温度,校验失败");
            return;
        }
        if (data == null || data.length < 10) {
            return;
        }
        //`A5 5A``01``00 08``03``01``0C B7`
        int tecTemp = ((data[7] & 0xff) << 8) + (data[8] & 0xff);

        //设置当前温度
        float currentTemp = tecTemp / 100f;
        runOnUiThread(() -> {
            tempTv.setText(currentTemp + "");
        });
    }

    /**
     * 读取pid任务
     */
    private class ReadTempTask implements Runnable {
        @Override
        public void run() {
            try {
                byte[] cmd = Cmd.queryTemp(1);
                serialPortHelper.open();//打开串口
                Bundle bundle = serialPortHelper.execute(cmd);
                boolean isSuc = bundle.getBoolean("suc");
                byte[] data = bundle.getByteArray("data");
                onCallback(isSuc, data);
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            } finally {
                serialPortHelper.close();
            }
        }
    }

    @Override
    protected int layoutResId() {
        return R.layout.activity_test_temp;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initViews();
        serialPortHelper = new SerialPortHelper(new SerialPortDevice(AppConfig.SERIAL_PORT, AppConfig.SERIAL_BAUD_RATE));
        this.executor = Executors.newScheduledThreadPool(1);
        try {
            executor.schedule(new ReadTempTask(), 0, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("StaticFieldLeak")
    private void initViews() {
        titleTv.setText("机械测试");
        targetTempLl.setOnClickListener(v -> {
            new DialogView2(this)
                    .setTitle("设置目标温度")
                    .setHint("请输入目标温度")
                    .setContentNumberType()
                    .setOnClickListener(content -> {
                        //A5 5A``01``00 08``03`36`0C B7`
                        targetTempTv.setText(content);
                        writeAsyncTask = new WriteAsyncTask("保存中...", Float.valueOf(content));
                        writeAsyncTask.execute();
                    }).show();
        });
    }

    @Override
    protected void onDestroy() {
        if (writeAsyncTask != null) {
            writeAsyncTask.cancel(true);
        }
        if (serialPortHelper != null) {
            serialPortHelper.close();
        }
        super.onDestroy();
    }

    public void showLoading(String content) {
        if (dialog == null) {
            dialog = new Dialog(this, R.style.DimDialogStyle);
            dialog.setContentView(R.layout.dialog_loading);
            dialog.setCanceledOnTouchOutside(true);
            dialog.setCancelable(true);
        }
        TextView contentTv = dialog.findViewById(R.id.content_tv);
        contentTv.setText(content);
        dialog.show();
    }

    public void dismissLoading() {
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    @SuppressLint("StaticFieldLeak")
    class WriteAsyncTask extends AsyncTask<Void, Void, Boolean> {
        private String loadingText;
        private float value;

        WriteAsyncTask(String loadingText, float value) {
            this.loadingText = loadingText;
            this.value = value;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoading(loadingText);
        }

        @SuppressLint("WrongThread")
        @Override
        protected Boolean doInBackground(Void... voids) {
            try {
                serialPortHelper.open();//打开串口
                Bundle bundle = serialPortHelper.execute(Cmd.setTemp(1, value));
                boolean isSuc = bundle.getBoolean("suc");
                if (isSuc) {
                    byte[] data = bundle.getByteArray("data");
                    if (Cmd.cmdValidate(data)) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
                return false;
            } finally {
                serialPortHelper.close();
            }
        }

        @Override
        protected void onPostExecute(Boolean result) {
            dismissLoading();
            if (result) {
                ToastUtils.get().showText("保存成功");
            } else {
                ToastUtils.get().showText("保存失败");
            }
        }
    }


}
